<?php
/*
 * @Date: 2020-09-12 23:36:27
 * @名称: 漫画 - 获取漫画详细信息
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑: 初雪桜
 * @LastEditTime: 2021-01-29 00:46:10
 * @FilePath: /Site/app/api/controller/Comics/Get/GetComicsInfo.php
 */

namespace app\api\controller\Comics\Get;

use app\BaseController;
use think\facade\Db;

class GetComicsInfo extends BaseController
{

    public function StartGetComicsInfo(
        $book_id
    ) {
        $RequestAuthenticationAndUserAuthentication = RequestAuthenticationAndUserAuthentication(true, true, true, true, config('debug.debug'));
        if ($RequestAuthenticationAndUserAuthentication['code'] != 200) { //判断是否都验证通过了
            #没有验证通过
            return json($RequestAuthenticationAndUserAuthentication);
        }

        $data["code"] = "200";
        $data["message"] = "success";
        $data["data"]['comic']["_id"] = $book_id; //漫画id
        $info = Db::table("book_info")
            ->alias('book_info')
            ->where([
                "book_info._id" => $book_id,
            ])
            ->leftJoin("book_list book_list", "book_list._id = book_info._id") //查询漫画信息
            ->join('user_info user_info', 'user_info._id = book_list.user_id')
            ->join('user_info_table_name', 'user_info_table_name._id = book_list.user_id')
            ->field(
                [
                    //! 用户类
                    "user_info._id as userInfoId", //发布者id
                    "user_info.gender as userInfoGender", //性别 0机器人 1男性 2 女性
                    "user_info.name as userInfoName", //发布者 昵称
                    "user_info.slogan as userInfoSlogan", //发布者 个性签名
                    "user_info.verified as userInfoVerified", //认证用户 真假
                    "user_info.exp as userInfoExp", //经验
                    // "user_info.title as userInfoTitle", //发布者 等级名称 类似于冒泡潜水之类的
                    // "user_info.level as userInfolevel", //等级 数据库已删除此项
                    "user_info.characters as userInfoCharacters", //不知道干什么的
                    "user_info.file_server as userInfoFileServer", //头像服务器
                    "user_info.path as userInfoPath", //头像路径
                    "user_info.original_name as userInfoOriginalName", //保存的名字
                    "user_info.character as userInfoCharacter", //头像框
                    "user_info_table_name.book_like_table_name as userLikeTable", //用户喜欢表
                    //?书籍类
                    "book_list.title as bookInfoTitle", //书籍名
                    "book_list.original_name as bookInfoOriginalName", //保存文件名 - 封面图片
                    "book_list.path as bookInfoPath", //文件路径 - 封面图片
                    "book_list.file_server as bookInfoFileServer", //文件地址 - 封面图片
                    "book_list.created_at as bookInfoCreated_at", //开始时间
                    "book_list.comment_table_name as comment_table_name", //开始时间
                    "book_info.categories as bookInfoCategories", //分类
                    "book_info.tags as bookInfoTags", //标签
                    "book_info.finished as bookInfoFinished", //是否完结
                    "book_info.updated_at as bookInfoUpdated_at", //最后更新时间
                    "book_info.allow_download as bookInfoAllowDownload", //是否允许下载
                    "book_info.allow_comment as bookInfoAllowComment", //是否允许评论
                    "book_info.total_likes as bookInfoTotalLikes",
                    "book_info.description as bookInfoDescription", //描述
                    "book_info.likes_count as likesCount", //头像框
                    "book_info.total_views as bookInfoTotalViews",
                    "book_info.views_count as bookInfoViewsCount",
                    "book_info.is_favourite as bookInfoIsFavourite",
                    // "book_info.is_liked as bookInfoIsLiked",
                    "book_info.comments_count as bookInfoCommentsCount",
                ]
            )
            ->find();
        // 查询等级
        $level_info = Db::table('user_level')
            ->where([
                ["min_experience", "<=", $info['userInfoExp']],
                ["max_experience", ">=", $info['userInfoExp']]
            ])
            ->field([
                "level_name", //等级名
                "level" //等级
            ])
            ->find();
        $info['userInfoTitle'] = $level_info['level_name'];
        $info['userInfolevel'] = $level_info['level'];
        //查询作者 / 协作者 
        $authorOrChineseTeam = Db::table('author_and_chinese_team')
            ->where([
                "author_and_chinese_team.book_id" => $book_id,
                "author_and_chinese_team.state" => 0,
            ])
            ->alias('author_and_chinese_team')
            ->join('user_info user_info', 'user_info._id = author_and_chinese_team.user_id')
            ->field([
                "author_or_chinese_team",
                "user_info.name",
                "user_info._id",
            ])
            ->select();

        if ($info == null || !$authorOrChineseTeam) {
            //判断有没有这本书
            return json([
                "code" => 400, "error" => '1022', "message" => 'invalid id', "detail" => ':('
            ]);
        }
        //生成 协作者 / 创作者 字符串
        $bookInfoAuthor = [];
        $bookInfoChineseTeam = [];
        foreach ($authorOrChineseTeam as $key => $value) {
            if ($value['author_or_chinese_team'] == 0) {
                array_push($bookInfoAuthor, [
                    "name" => $value['name'],
                    "user_id" => $value['_id'],
                ]);
            } else {
                array_push($bookInfoChineseTeam, [
                    "name" => $value['name'],
                    "user_id" => $value['_id'],
                ]);
            }
        }

        // 重新赋值
        //上传者信息
        $data["data"]['comic']["_creator"]['_id'] = $info["userInfoId"];
        switch ($info["userInfoGender"]) {
            case 0:
                $data["data"]['comic']["_creator"]['gender'] = "机器人";

                break;
            case 1:
                $data["data"]['comic']["_creator"]['gender'] = "男性";

                break;
            case 2:
                $data["data"]['comic']["_creator"]['gender'] = "女性";

                break;

            default:
                # code...
                break;
        }
        $data["data"]['comic']["_creator"]['name'] = $info["userInfoName"];
        $data["data"]['comic']["_creator"]['slogan'] = $info["userInfoSlogan"];
        $data["data"]['comic']["_creator"]['verified'] = ($info["userInfoVerified"]) ? true : false;
        $data["data"]['comic']["_creator"]['exp'] = $info["userInfoExp"];
        $data["data"]['comic']["_creator"]['title'] = $info["userInfoTitle"];
        $data["data"]['comic']["_creator"]['level'] = $info["userInfolevel"];
        $data["data"]['comic']["_creator"]['characters'] = ["knight"];
        $data["data"]['comic']["_creator"]['role'] = "knight"; //这里写死不知道干啥的
        $data["data"]['comic']["_creator"]['avatar']['fileServer'] = $info["userInfoFileServer"];
        $data["data"]['comic']["_creator"]['avatar']['path'] = $info["userInfoPath"];
        $data["data"]['comic']["_creator"]['avatar']['originalName'] = $info["userInfoOriginalName"];
        $data["data"]['comic']["_creator"]['character'] = $info["userInfoCharacter"];
        //上传者信息
        $data["data"]['comic']["title"] = $info["bookInfoTitle"];
        $data["data"]['comic']["description"] = $info["bookInfoDescription"];
        $data["data"]['comic']["thumb"]['originalName'] = $info["bookInfoOriginalName"];
        $data["data"]['comic']["thumb"]['path'] = $info["bookInfoPath"];
        $data["data"]['comic']["thumb"]['fileServer'] = $info["bookInfoFileServer"];
        $data["data"]['comic']["author"] = $bookInfoAuthor;
        $data["data"]['comic']["chineseTeam"] = $bookInfoChineseTeam;
        $data["data"]['comic']["categories"] = explode(",", $info["bookInfoCategories"]);
        $data["data"]['comic']["tags"] =  ($info["bookInfoTags"]) ? explode(",", $info["bookInfoTags"]) : [];
        $data["data"]['comic']["pagesCount"] = Db::table("book_info_project")->where("_id", '=', $book_id)->count(); // 总章节
        $data["data"]['comic']["epsCount"] = Db::table("book_info_project")->where("_id", '=', $book_id)->sum("images_count"); //总页数
        $data["data"]['comic']["finished"] = ($info["bookInfoFinished"]) ? true : false;
        $data["data"]['comic']["updated_at"] = $info["bookInfoUpdated_at"];
        $data["data"]['comic']["created_at"] = $info["bookInfoCreated_at"];
        $data["data"]['comic']["allowDownload"] = ($info["bookInfoAllowDownload"]) ? true : false;
        $data["data"]['comic']["allowComment"] = ($info["bookInfoAllowComment"]) ? true : false;
        $data["data"]['comic']["totalLikes"] = $info["bookInfoTotalLikes"];
        $data["data"]['comic']["totalViews"] = $info["bookInfoTotalViews"];
        $data["data"]['comic']["viewsCount"] = $info["bookInfoViewsCount"];
        $data["data"]['comic']["likesCount"] = $info['likesCount']; //喜欢数量
        $data["data"]['comic']["isFavourite"] = ($info["bookInfoIsFavourite"]) ? true : false;
        try { //@x 用户喜欢表是从用户表登陆处查询出来的 不一定存在此表 
            $data["data"]['comic']["isLiked"] = (Db::table($info['userLikeTable'])
                ->where(["book_id" => $book_id, "user_id" => $RequestAuthenticationAndUserAuthentication['data']['userVersion']['data']["_id"]])
                ->find()) ? true : false;
        } catch (\Throwable $error) {
            //@a 不存在表
            return errorJsonReturn("Server-DataBase-10001", "请联系管理员", 0, [
                "Line" => $error->getLine(),
                "Code" => $error->getCode(),
                "Message" => $error->getMessage(),
                "File" => $error->getFile(),
            ], false);
        }
        $data["data"]['comic']["commentsCount"] = (Db::table($info['comment_table_name'])
            ->where(["book_id" => $book_id,])
            ->count()); //评论数量
        return json($data);
    }
}
